package job.manager.client.mb;

import com.icesoft.faces.component.ext.RowSelectorEvent;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import org.springframework.security.context.SecurityContextHolder;
import javax.faces.event.ActionEvent;
import job.manager.db.ec.UsersEB;
import job.manager.db.sb.UserRemote;
import job.manager.icefaces.core.SortableList;
import com.icesoft.faces.component.ext.HtmlCommandButton;
import java.util.Arrays;
import java.util.Comparator;

/**
 *  The user DataTable ManagedBean is responsible for connection to the Enterprise Beans
 *  and providing the pages/user with the information about users.
 *  Also resposible for editing and removing users.
 *
 */
public class UserMBDT extends SortableList implements Serializable {

    @EJB
    private UserRemote userBean;
    private UsersEB selectedUser;
    // UserEB Names
    private static final String idColumnName = "id";
    private static final String userNameColumnName = "username";
    private static final String emailColumnName = "email";
    private static final String isAdminColumnName = "isAdmin";
    private static final String profileColumnName = "profileId";
    private static final String userGroupColumnName = "usergroup";
    // UserEB header texts
    private static final String idColumnHeader = "Id";
    private static final String userNameColumnHeader = "Användarnamn";
    private static final String emailColumnHeader = "E-mail";
    private static final String isAdminColumnHeader = "Administrator";
    private static final String profileColumnHeader = "Profil id";
    private static final String userGroupColumnHeader = "Användargrupp";
    private Object[] userList;

    /** Creates a new instance of UserMBDT */
    public UserMBDT() {
        super(idColumnName);
    }

    @PostConstruct
    public void onInit() {
        selectedUser = null;
        this.checkIfNotAdmin();
    }

    //for display if not admin
    protected void checkIfNotAdmin() {
        this.problemSolver();
        String userNamn = SecurityContextHolder.getContext().getAuthentication().getName();
        UsersEB currentUser = userBean.findUser(userNamn);
        if(!currentUser.getIsAdmin()) {
            selectedUser = currentUser;
        }
    }

    //Spring security bug fix
    private void problemSolver()
    {
        if(this.userBean==null)
            this.userBean = ConnectFactory.getUserBean();
    }

    //load all users
    public void loadUsers() {
        this.problemSolver();
        userList = userBean.getAllUsers().toArray();
    }

    //providing the DataTable 
    public Object[] getUsers() {
        if (userList == null) {
            this.loadUsers();
        }
        if (!oldSort.equals(sortColumnName) ||
                oldAscending != ascending) {
            sort();
            oldSort = sortColumnName;
            oldAscending = ascending;
        }
        return userList;
    }

    //sorting the list according to the pushed header in the DataTable
    @Override
    protected void sort() {
        Comparator comparator = new Comparator() {

            public int compare(Object o1, Object o2) {
                UsersEB u1 = (UsersEB) o1;
                UsersEB u2 = (UsersEB) o2;

                if (sortColumnName == null) {
                    return 0;
                }
                if (sortColumnName.equals(idColumnName)) {
                    return ascending ? new Integer(u1.getId()).compareTo(new Integer(u2.getId())) : new Integer(u2.getId()).compareTo(new Integer(u1.getId()));
                } else if (sortColumnName.equals(userNameColumnName)) {
                    return ascending ? u1.getUserName().compareTo(u2.getUserName()) : u2.getUserName().compareTo(u1.getUserName());
                } else if (sortColumnName.equals(emailColumnName)) {
                    return ascending ? u1.getEmail().compareTo(u2.getEmail()) : u2.getEmail().compareTo(u1.getEmail());
                } else if (sortColumnName.equals(isAdminColumnName)) {
                    return ascending ? new Boolean(u1.getIsAdmin()).compareTo(new Boolean(u2.getIsAdmin())) : new Boolean(u2.getIsAdmin()).compareTo(new Boolean(u1.getIsAdmin()));
                } else if (sortColumnName.equals(profileColumnName)) {
                    Integer pid1 = Integer.MAX_VALUE;
                    Integer pid2 = Integer.MAX_VALUE;
                    if( u1.getProfileId() != null )
                       pid1 = new Integer(u1.getProfileId());
                    if( u2.getProfileId() != null)
                        pid2 = new Integer(u2.getProfileId());
                    return ascending ? pid1.compareTo(pid2) : pid2.compareTo(pid1);
                } else {
                    return 0;
                }
            }
        };
        Arrays.sort(userList, comparator);
    }

    //returns if the default sorting is ascending
    @Override
    protected boolean isDefaultAscending(String sortColumn) {
        return true;
    }

    //Action for deleting user
    public void deleteAction(ActionEvent arg) {
        if (arg.getComponent() instanceof HtmlCommandButton) {
            if (this.selectedUser != null) {
                userBean.deleteUser(this.selectedUser);
                this.loadUsers();
            }
        }
    }

    //Action for updating user
    public void updateAction(ActionEvent arg) {
        if (this.selectedUser != null) {
            this.userBean.updateUser(selectedUser);
        }
    }

    //Action for selecting user
    public void selectAction(RowSelectorEvent arg) {
        this.selectedUser = (UsersEB) userList[arg.getRow()];
    }

    /** column names */
    public String getIdColumnName() {
        return idColumnName;
    }

    public String getUserColumnName() {
        return userNameColumnName;
    }

    public String getEmailColumnName() {
        return emailColumnName;
    }

    public String getIsAdminColumnName() {
        return isAdminColumnName;
    }

    public String getProfileColumnName() {
        return profileColumnName;
    }

    /** header texts */
    public String getEmailColumnHeader() {
        return emailColumnHeader;
    }

    public String getIdColumnHeader() {
        return idColumnHeader;
    }

    public String getIsAdminColumnHeader() {
        return isAdminColumnHeader;
    }

    public String getProfileColumnHeader() {
        return profileColumnHeader;
    }

    public String getUserGroupColumnHeader() {
        return userGroupColumnHeader;
    }

    public String getUserNameColumnHeader() {
        return userNameColumnHeader;
    }

    //get the selected user
    public UsersEB getSelectedUser() {
        this.checkIfNotAdmin();
        if (selectedUser != null) {
            return selectedUser;
        }
       return new UsersEB();
    }

    //get if have a selected user
    public boolean getIsEditing() {
        this.checkIfNotAdmin();
        return (this.selectedUser == null);
    }
}
